package org.arch_learn.spring_cloud.sca_homework.service_user.service.impl;

import org.apache.dubbo.config.annotation.Reference;
import org.arch_learn.spring_cloud.sca_homework.service_common_dependency.dubbo_api.ICodeDubboService;
import org.arch_learn.spring_cloud.sca_homework.service_common_dependency.pojo.Account;
import org.arch_learn.spring_cloud.sca_homework.service_user.repository.IUserRepository;
import org.arch_learn.spring_cloud.sca_homework.service_user.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.UUID;

@Service
public class UserService implements IUserService {
    @Reference(check = false)
    private ICodeDubboService ICodeDubboService;
    @Autowired
    private IUserRepository userRepository;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Boolean register(String email, String password, String code) {
        Boolean result = false;
        Integer body = ICodeDubboService.validateCode(email, code);
        if (body == 0) {
            Account account = new Account();
            account.setEmail(email);
            account.setCreator(email);
            account.setCreateDate(new Date());
            userRepository.save(account);
            result = true;
        }
        return result;
    }

    @Override
    public Boolean isRegistered(String email) {
        Account account = new Account();
        account.setEmail(email);
        Example<Account> example = Example.of(account);
        return userRepository.findOne(example).isPresent();
    }

    @Override
    public ResponseEntity<String> login(String email, String password, HttpServletResponse httpServletResponse) {
        Account account = new Account();
        account.setEmail(email);
        account.setPassword(password);
        Example<Account> accountExample = Example.of(account);
        boolean present = userRepository.findOne(accountExample).isPresent();
        ResponseEntity responseEntity;
        if (present) {
            UUID uuid = UUID.randomUUID();
            String tokenVal = uuid.toString();
            Cookie token = new Cookie("token", tokenVal);
            httpServletResponse.addCookie(token);
            responseEntity = ResponseEntity.ok(email);
            HashMap<String, String> map = new HashMap<>();
            map.put("email", email);
            map.put("password", password);
            stringRedisTemplate.opsForHash().putAll("auth:" + tokenVal, map);
        } else {
            responseEntity = ResponseEntity.badRequest().body("bad credential!");
        }
        return responseEntity;
    }
}
